//
//  DictExtension.swift
//  Intersection
//
//  Created by 我骑着蜗牛走天下 on 2025/2/25.
//

import Foundation

enum EncodeError: Error{
    case error(String)
}

public extension Dictionary{
    
    /// 转 ase64URL 加密
    /// 在转换失败时返回 nil
    public func toBase64URL() -> String? {
        // 序列化 JSON
        guard let jsonData = try? JSONSerialization.data(withJSONObject: self, options: .sortedKeys) else {
            return nil
        }
        
        // 转换为 Base64URL
        let base64 = jsonData.base64EncodedString()
        return base64
            .replacingOccurrences(of: "+", with: "-")
            .replacingOccurrences(of: "/", with: "_")
            .replacingOccurrences(of: "=", with: "")
    }
    
    
    /// 转json格式的data
    public func toJsonData()->Data?{
        
        if (!JSONSerialization.isValidJSONObject(self)) {
            debugLog("DictionaryToJsonData 无法解析出JSON")
            return Data()
        }
        do {
            let data : Data = try JSONSerialization.data(withJSONObject: self, options: [])
            return data
        }catch{
            debugLog("DictionaryToJsonData 解析失败")
            return nil
        }
        
    }
    
    /// 转json字符串 prettyPrinted：换行和缩减
    func toJSONString(prettyPrinted: Bool = true) -> String {
        guard JSONSerialization.isValidJSONObject(self) else { return "nil" }
        let options: JSONSerialization.WritingOptions = prettyPrinted ? [.prettyPrinted, .withoutEscapingSlashes] : []
        if let data = try? JSONSerialization.data(withJSONObject: self, options: options),
            var jsonString = String(data: data, encoding: .utf8) {
            return jsonString
        }
        return "nil"
    }
    
    /// 删除字典中的空数组
    public func removingEmptyArrays() -> [Key: Value] {
       return self.filter { key, value in
           if let array = value as? [Any] {
               return !array.isEmpty
           }
           return true
       }
   }
    
}


public extension Dictionary<String,String> {
    
    ///删除字典中的空字符串值
    public func removeNullCharacterValue() -> [String:Any]{
        var vdic = self
        vdic.keys.forEach{
            let str = vdic[$0]
            if str != nil && str == "" {
                vdic.removeValue(forKey: $0)
            }
        }
        return vdic
    }
    
}

